<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :sm="24" :md="24" :xxl="16" v-if="!isBusiness">
            <a-form-item label="区域">
              <a-row :gutter="5" type="flex">
                <a-col :span="3">
                  <a-select
                    placeholder="省"
                    v-model="queryParam.provinceCode"
                    @change="e => addressChange(e, 'cityOptions', 'province')"
                  >
                    <a-select-option v-for="item in provinceOptions" :key="item.name" :value="item.code">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-col>
                <a-col :span="3">
                  <a-select
                    placeholder="市"
                    v-model="queryParam.cityCode"
                    @change="e => addressChange(e, 'areaOptions', 'city')"
                  >
                    <a-select-option v-for="item in cityOptions" :key="item.name" :value="item.code">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-col>
                <a-col :span="3">
                  <a-select
                    placeholder="区"
                    v-model="queryParam.areaCode"
                    @change="e => addressChange(e, 'streetOptions', 'area')"
                  >
                    <a-select-option v-for="item in areaOptions" :key="item.name" :value="item.code">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-col>
                <a-col :span="3">
                  <a-select
                    placeholder="街道"
                    v-model="queryParam.streetCode"
                    @change="e => addressChange(e, '', 'street')"
                  >
                    <a-select-option v-for="item in streetOptions" :key="item.name" :value="item.code">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-col>
                <a-col :span="4">
                  <a-select
                    placeholder="商家"
                    v-model="queryParam.businessId"
                    @change="e => agentChange(e, 'networkOptions', 'agentCode')"
                  >
                    <a-select-option v-for="item in agentOptions" :key="item.name" :value="item.code">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-col>
                <a-col :span="4">
                  <a-select
                    placeholder="网点"
                    v-model="queryParam.networkId"
                    @change="e => agentChange(e, 'deviceOptions', 'networkCode')"
                  >
                    <a-select-option v-for="item in networkOptions" :key="item.name" :value="item.code">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-col>
                <a-col :span="4">
                  <a-select placeholder="设备" v-model="queryParam.deviceId">
                    <a-select-option v-for="item in deviceOptions" :key="item.name" :value="item.code">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-col>
              </a-row>
            </a-form-item>
          </a-col>
          <a-col :sm="24" :md="12" :xl="8">
            <a-form-item label="提现类型">
              <j-dict-select-tag
                allowClear
                v-model="queryParam.withdrawType"
                placeholder="请选择"
                dictCode="withdrawType"
              />
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus || isBusiness">
            <a-col :sm="24" :md="12" :xl="8">
              <a-form-item label="提现状态">
                <j-dict-select-tag
                  allowClear
                  v-model="queryParam.status"
                  placeholder="请选择"
                  dictCode="withdrawStatus"
                />
              </a-form-item>
            </a-col>
            <a-col :sm="24" :md="12" :xl="8">
              <a-form-item label="创建时间">
                <a-range-picker allowClear class="per100" v-model="tempTimes" @change="timeChange" />
              </a-form-item>
            </a-col>
          </template>

          <a-col :sm="24" :md="12" :xl="8">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button @click="searchReset()" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px" v-if="!isBusiness">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <a-row :gutter="24" v-if="role === 'business'">
      <!-- 线上收入 -->
      <a-col :sm="24" :md="12" :xl="12" :style="{ marginBottom: '24px' }">
        <div class="box t-c">
          <a-icon type="pay-circle" class="icon bg-blue" />
          <div class="fz24 bold">{{ withdrawnAmount }}元</div>
          <div>已提现金额</div>
        </div>
      </a-col>
      <!-- 线上收入 -->
      <a-col :sm="24" :md="12" :xl="12" :style="{ marginBottom: '24px' }">
        <div class="box t-c">
          <div class="pointer" @click="showModal(undrawnAmount, 'WithdrawApplyRef')">
            <a-icon type="pay-circle" class="icon bg-purpler" />
            <div class="fz24 bold blue">{{ undrawnAmount }}元</div>
            <div>未提现金额<span class="green">（点击申请提现）</span></div>
          </div>
        </div>
      </a-col>
    </a-row>

    <!-- table区域 -->
    <a-table
      ref="table"
      bordered
      size="middle"
      rowKey="id"
      :columns="columns"
      :dataSource="dataSource"
      :pagination="ipagination"
      :loading="loading"
      :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      :scroll="{ x: 1200 }"
      @change="handleTableChange"
    >
      <span slot="withdrawnType" slot-scope="text, record">
        <a-tag color="#04de6d" v-if="text === '1'">
          {{ filterDictText(withdrawTypeOptions, text) }}
        </a-tag>
        <a-tag color="#722ed1" v-else-if="text === '2'">
          {{ filterDictText(withdrawTypeOptions, text) }}
        </a-tag>
      </span>

      <span slot="action" slot-scope="text, record" v-if="record.status === '0' && isAdmin">
        <a-button @click="showModal(record, 'WithdrawAuditRef')" type="primary" class="ml5 mr5" size="small"
          >审批</a-button
        >
      </span>
    </a-table>

    <!-- 申请提现 -->
    <withdraw-apply ref="WithdrawApplyRef" @ok="refresh()"></withdraw-apply>
    <withdraw-audit ref="WithdrawAuditRef" @ok="refresh()"></withdraw-audit>
  </a-card>
</template>

<script>
import store from '@/store/'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import Api from '@/api/CashManage/FundsWithdrawal'
import AgentManage from '@api/AgentManage/AgentManage'
import { initDictOptions, filterDictText } from '@/components/dict/JDictSelectUtil'
import WithdrawApply from './Modal/WithdrawApply.vue'
import { formatAmountFromFenToYuan } from '@/utils/util'
import WithdrawAudit from '@views/CashManage/Modal/WithdrawAudit'
import { getAction } from '@api/manage'
import { RoleMixin } from '@/mixins/roleUtil'

export default {
  name: 'FundsWithdrawal',
  mixins: [JeecgListMixin, RoleMixin],
  components: { WithdrawApply, WithdrawAudit },
  data() {
    return {
      filterDictText,
      url: {
        list: Api.sysUserWithdrawalList,
        account: AgentManage.account
      },
      role: '',
      columns: [],
      withdrawTypeOptions: [],
      withdrawStatusOptions: [],
      formatAmountFromFenToYuan,
      accountInfo: {
        undrawnAmount: 0,
        withdrawnAmount: 0
      },
      userId: ''
    }
  },
  created() {
    this.columns = [
      {
        title: '代理商编号',
        align: 'center',
        dataIndex: 'businessId',
        sorter: (a, b) => {
          return a.businessId - b.businessId
        }
      },
      {
        title: '代理商',
        align: 'center',
        dataIndex: 'businessName'
      },
      {
        title: '提现申请金额（元）',
        dataIndex: 'withdrawalAmount',
        align: 'center',
        customRender: (text, record, index) => {
          return formatAmountFromFenToYuan(text)
        },
        sorter: (a, b) => {
          return a.withdrawalAmount - b.withdrawalAmount
        }
      },
      {
        title: '已提现金额（元）',
        dataIndex: 'withdrawnAmount',
        align: 'center',
        customRender: (text, record, index) => {
          return formatAmountFromFenToYuan(text)
        },
        sorter: (a, b) => {
          return a.withdrawnAmount - b.withdrawnAmount
        }
      },
      {
        title: '提现方式',
        dataIndex: 'withdrawnType',
        align: 'center',
        scopedSlots: { customRender: 'withdrawnType' },
        sorter: (a, b) => {
          return a.withdrawnType - b.withdrawnType
        }
      },
      {
        title: '状态',
        dataIndex: 'status',
        align: 'center',
        customRender: (text, record, index) => {
          //字典值替换通用方法
          return filterDictText(this.withdrawStatusOptions, text)
        },
        sorter: (a, b) => {
          return a.status - b.status
        }
      },
      {
        title: '备注',
        align: 'center',
        dataIndex: 'remark',
        sorter: (a, b) => {
          return a.remark - b.remark
        }
      },
      {
        title: '审批人',
        align: 'center',
        dataIndex: 'approver',
        sorter: (a, b) => {
          return a.approver - b.approver
        }
      },
      {
        title: '审批时间',
        align: 'center',
        dataIndex: 'approveTime',
        sorter: (a, b) => {
          return a.approveTime - b.approveTime
        }
      },
      {
        title: '创建时间',
        align: 'center',
        dataIndex: 'createTime',
        sorter: (a, b) => {
          return a.createTime - b.createTime
        }
      },
      {
        title: '操作',
        dataIndex: 'action',
        scopedSlots: { customRender: 'action' },
        fixed: 'right',
        width: 100
      }
    ]
    if (this.hasRole('admin') || this.hasRole('developer')) {
      this.role = 'admin'
    } else if (this.hasRole('business') || this.hasRole('agent')) {
      this.role = 'business'
    }
    this.initDictConfig()
    this.getAddress('provinceOptions')
    this.userId = store.getters.userInfo.id
  },
  mounted() {
    this.getAccount()
  },
  computed: {
    undrawnAmount() {
      return `${formatAmountFromFenToYuan(this.accountInfo.undrawnAmount)}`
    },
    withdrawnAmount() {
      return `${formatAmountFromFenToYuan(this.accountInfo.withdrawnAmount)}`
    },
    isAdmin() {
      return !!store.getters.roles.find(item => {
        return item.roleCode === 'admin'
      })
    }
  },
  methods: {
    async refresh() {
      this.getAccount()
      this.dataSource = []
      await this.loadData()
      this.$forceUpdate()
    },
    getAccount() {
      getAction(this.url.account).then(res => {
        if (res.code === 200) {
          this.$nextTick(() => {
            this.accountInfo = res.result || {}
          })
        }
      })
    },
    // 初始化数据字典
    initDictConfig() {
      //初始化字典 - 提现方式
      initDictOptions('withdrawType').then(res => {
        if (res.success) {
          this.withdrawTypeOptions = res.result
        }
      })
      //初始化字典 - 审批状态
      initDictOptions('withdrawStatus').then(res => {
        if (res.success) {
          this.withdrawStatusOptions = res.result
        }
      })
    },

    // 创建时间改变
    timeChange(e, arr) {
      if (arr[0]) {
        this.queryParam.startTime = arr[0]
        this.queryParam.endTime = arr[1]
      } else {
        this.queryParam.startTime = undefined
        this.queryParam.endTime = undefined
      }
    },

    // 展示弹窗
    showModal(record, name) {
      this.$refs[name].showModal(record)
    },

    hasRole(name) {
      const hasRole = store.getters.roles.find(item => {
        return item.roleCode === name
      })
      return !!hasRole
    }
  }
}
</script>

<style lang="less" scoped>
.icon {
  font-size: 30px;
  border-radius: 50%;
}

.bg-blue {
  color: #1890ff;
  background: #e6f7ff;
}

.bg-purpler {
  color: #722ed1;
  background: #f9f0ff;
}

.blue {
  color: #1890ff;
}

.green {
  color: #52c41a;
}

.pointer {
  cursor: pointer;
}

.box {
  padding: 20px 0;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(#000, 0.1);
  .pointer {
    display: inline-block;
    vertical-align: top;
  }
}
</style>

